const fs = require('fs');
const path = require('path');
const puppeteer = require('puppeteer');

async function exportToPDF() {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  
  // 等待本地服务器启动
  await new Promise(resolve => setTimeout(resolve, 2000));
  
  // 访问本地构建的文档
  await page.goto('http://localhost:4173', {
    waitUntil: 'networkidle0'
  });
  
  // 生成PDF
  await page.pdf({
    path: 'VisionGroup3-OpenDoc.pdf',
    format: 'A4',
    printBackground: true,
    margin: {
      top: '20mm',
      bottom: '20mm',
      left: '10mm',
      right: '10mm'
    }
  });
  
  console.log('PDF导出完成：VisionGroup3-OpenDoc.pdf');
  await browser.close();
}

// 启动预览服务器并导出PDF
const { spawn } = require('child_process');
const server = spawn('npm', ['run', 'docs:preview'], { stdio: 'pipe' });

server.stdout.on('data', (data) => {
  console.log(`服务器: ${data}`);
  if (data.toString().includes('Local:')) {
    exportToPDF().then(() => {
      server.kill();
      process.exit(0);
    });
  }
});

server.stderr.on('data', (data) => {
  console.error(`错误: ${data}`);
});

setTimeout(() => {
  console.error('服务器启动超时');
  server.kill();
  process.exit(1);
}, 30000);
